<div class="page-header">
    <h1>
        Form Pembelian Produk
        <small>
            <i class="icon-double-angle-right"></i>
            Form Pembelian Produk Agent
        </small>
    </h1>
</div>

<?php
if ($this->msg != "") {
    ?>
    <div class="alert alert-info">
        <button type="button" class="close" data-dismiss="alert">
            <i class="icon-remove"></i>
        </button>

        <strong>
            <i class="icon-ok"></i>
        </strong>

        <?php echo $this->msg; ?>
        <br />
    </div>
    <?php
}
if ($this->errmsg) {
    ?>
    <div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert">
            <i class="icon-remove"></i>
        </button>

        <strong>
            <i class="icon-remove"></i>

        </strong>

        <?php echo $this->errmsg; ?>
        <br />
    </div>
<?php
}

if ($this->msg == "") {

 ?>

<div class="row">
    <div class="col-xs-11">
            <!-- PAGE CONTENT BEGINS -->
            <div class="row-fluid">
                <div class="span12">
                            <div class="widget-main">
                                <div id="fuelux-wizard" class="row-fluid" data-target="#step-container">
                                    <ul class="wizard-steps">
                                        <li data-target="#step1" class="active">
                                            <span class="step">1</span>
                                            <span class="title">Input Jumlah Pembelian</span>
                                        </li>

                                        <li data-target="#step2">
                                            <span class="step">2</span>
                                            <span class="title">Metode Pembayaran</span>
                                        </li>

                                        <li data-target="#step3">
                                            <span class="step">3</span>
                                            <span class="title">Konfirmasi Pemesanan</span>
                                        </li>
                                    </ul>
                                </div>

                                <hr />

                                <form class="form-horizontal" id="inputForm" name="inputForm" method="post">
                                    <div class="step-content row-fluid position-relative" id="step-container">
                                        <div class="step-pane active" id="step1">
                                            <h3 class="lighter block green">Masukkan data pembelian Produk</h3>
                                            <br><br>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right" for="slSuplier"> Pilih Suplier </label>

                                                <div class="col-sm-9">
                                                    <select class="width-40 chosen-select" id="slSuplier" name="slSuplier" data-placeholder="Pilih Suplier..." rquired>
                                                        <option value=""> Pilih Suplier... </option>
                                                        <?php
                                                            foreach($this->supliers as $sup){
                                                                    echo '<option value="' . $sup['suplier_id'].'-'.$sup['suplier_name'].'">' . $sup['suplier_name']. ' ('. $sup['contact_city'].' - '.$sup['contact_province'].')</option>';
                                                            }

                                                        ?>
                                                    </select>
                                                </div>

                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right" for="slSuplier"> Pilih Agen </label>

                                                <div class="col-sm-9">
                                                    <select class="width-40 chosen-select" id="slAgen" name="slAgen" data-placeholder="Pilih Agen..." rquired>
                                                        <option value=""> Pilih Agen... </option>
                                                        <?php
                                                            foreach($this->agents as $agen){
                                                                    /*
                                                                    if ($agen['member_id'] == 100) $idAgen = $agen['member_id'];
                                                                    else $idAgen = $agen['member_reff_id'];
                                                                     * 
                                                                     */

                                                                    $idAgen = $agen['member_id'];

                                                                    echo '<option value="' . $idAgen.'-'.$agen['member_name'].'">(' . $agen['member_code']. ') '. $agen['member_name'].'</option>';
                                                            }

                                                        ?>
                                                    </select>
                                                </div>

                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right" for="sponsorId"> Pilih Produk </label>

                                                <div class="col-sm-9">
                                                    <select id="slProduct" name="slProduct" data-placeholder="Pilih Produk..." required>
                                                        <option value=""> Pilih Produk... </option>
                                                    </select>
                                                </div>

                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right" for="qty"> Jumlah Pembelian </label>

                                                    <div class="col-sm-9">
                                                        <input type="text" class="input-mini" id="qty" name="qty" />

                                                    </div>

                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label no-padding-right">&nbsp;</label>
                                                <div class="col-sm-9">
                                                    <button class="btn btn-success" type="button" id="btnTambah">
                                                        <i class="icon-ok bigger-110"></i>
                                                        Tambah
                                                    </button>
                                                </div>
                                            </div>
                                            <br>
                                            <table id="grid-table"></table>

                                            <div id="grid-pager"></div>
                                            <br>
                                            <div class="form-group">
                                                <label class="col-sm-9" id="lbTotalHarga"><b> Total Harga: 0</b></label>
                                                <input type="hidden" id="totalHarga" name="totalHarga"/>
                                            </div>

                                            <script type="text/javascript">
                                                    var $path_base = "/";//this will be used in gritter alerts containing images
                                            </script>

                                        </div>

                                        <div class="step-pane" id="step2">
                                            <div class="row-fluid">
                                                <h3 class="lighter block green">Pilih metode Pembayaran</h3>
                                                <br>
                                                <div class="form-group">
                                                    <?php
                                                    // Jika bukan agen hanya tukar point saja
                                                    if ($this->isAgent == ""){
                                                    ?>
                                                    <label for="inputWarning" class="col-xs-12 col-sm-3 control-label no-padding-right">&nbsp;&nbsp; </label>
                                                    <div class="radio">
                                                        <label>
                                                            <input name="rdPembayaran" type="radio" value="2" class="ace" id="rdTukarPoint" onclick="pilihBayar(this.value)" required/>
                                                            <span class="lbl"> Tukar Point (Point Anda: <?php echo number_format($this->balance);?>)</span>
                                                        </label>
                                                    </div>
                                                    <?php
                                                    }else{
                                                    ?>
                                                    <label for="rdPembayaran" class="col-xs-12 col-sm-3 control-label no-padding-right">&nbsp;&nbsp; </label>
                                                    <div class="radio">
                                                        <label>
                                                            <input name="rdPembayaran" type="radio" value="1" class="ace" onclick="pilihBayar(this.value)" required/>
                                                            <span class="lbl"> Cash</span>
                                                        </label>
                                                    </div>
                                                    
                                                    <label for="inputWarning" class="col-xs-12 col-sm-3 control-label no-padding-right">&nbsp;&nbsp; </label>
                                                    <div class="radio">
                                                        <label>
                                                            <input name="rdPembayaran" type="radio" value="3" class="ace" onclick="pilihBayar(this.value)" required />
                                                            <span class="lbl"> Transfer</span>
                                                        </label>
                                                    </div>
                                                    <label for="inputWarning" class="col-xs-12 col-sm-3 control-label no-padding-right">&nbsp;&nbsp; </label>
                                                    <div id="divBank" class="radio" style="visibility:hidden;position:absolute">
                                                        <label class="control-label no-padding-right" id="lbBank">&nbsp;&nbsp;
                                                        Transfer ke:
                                                        <?php
                                                        while ($this->accountsPT->next()) {
                                                                $res = $this->accountsPT->current();
                                                                echo "* Bank ".$res["bank_name"]." No Rek: ".$res["bank_acc_no"].", A/N: ".$res["bank_acc_name"]."<br>";
                                                        }
                                                        ?>
                                                        </label>
                                                    </div>
                                                     <?php
                                                    }
                                                    ?>
                                                    <input type="hidden" id="caraBayar" name="caraBayar" required/>
                                                </div>

                                            </div>
                                        </div>

                                        <div class="step-pane" id="step3">
                                            <div class="row-fluid">
                                                <h3 class="lighter block green">Konfirmasi Pembelian</h3>
                                                <small>
                                                        <i class="icon-double-angle-right"></i>
                                                        Klik Finish jika pesanan sudah benar.
                                                </small>

                                                <br>
                                                
                                                <table id="grid-table2"></table>

                                                <div id="grid-pager2"></div>
                                                <br>
                                                <div class="form-group">
                                                    <label class="col-sm-9" id="lbTotalHarga2"><b> Total Harga: 0</b></label>
                                                </div>
                                                <div class="form-group">
                                                    <label id="lbMetodeBayar" class="col-sm-9">Metode Pembayaran:&nbsp;&nbsp; </label>
                                                </div>
                                                <input type="hidden" id="dataPembelian" name="dataPembelian">
                                            </div>
                                        </div>


                                    </div>
                                    </form>
                                    <hr />
                                    <div class="row-fluid wizard-actions">
                                        <button class="btn btn-prev">
                                            <i class="icon-arrow-left"></i>
                                            Prev
                                        </button>

                                        <button class="btn btn-success btn-next" data-last="Finish ">
                                            Next
                                            <i class="icon-arrow-right icon-on-right"></i>
                                        </button>
                                    </div>

                            </div><!-- /widget-main -->


                </div>
            </div>
        <!-- PAGE CONTENT ENDS -->
    </div>
</div>
<script>

    var totalPoint = <?php echo ($this->balance == "") ? 0 : $this->balance;?>;
    var isAgent = '<?php echo $this->isAgent;?>';
    var minOrder = <?php echo ($this->minOrder == "") ? 0 : $this->minOrder;?>;

    //jumlah row:
    //alert(jQuery('#list6').jqGrid('getGridParam','records'));"


    $("select#slAgen").change(function(){

         var sup = $("#slSuplier").val().split("-");
         var agent = $("#slAgen").val().split("-");
         
         var options = '';

         if(sup != ""){

             options += '<option value="">== Loading Produk ==</option>';
             $("select#slProduct").html(options);
             $("select#slProduct").attr('disabled','disabled');

             $.getJSON("<?php echo $this->url() ?>/../../jsondata/getproducts",{slSuplier: sup[0], agent: agent[0], ajax: 'true'}, function(j){
                  options = '';
                  options += '<option value=""> Pilih Produk... </option>';
                  for (var i = 0; i < j.length; i++) {
                    if (isAgent == "")
                        options += '<option value="' + j[i].product_id + '~' +j[i].product_name+ '~' +j[i].member_price + '~' + j[i].qty + '">' + j[i].product_name + ' (Harga: '+ j[i].member_price +', Stok: '+ j[i].qty +')</option>';
                    else
                        options += '<option value="' + j[i].product_id + '~' +j[i].product_name+ '~' +j[i].agent_price + '~' + j[i].qty + '">' + j[i].product_name + ' (Harga: '+ j[i].agent_price +', Stok: '+ j[i].qty +')</option>';
                    
                    //options += '<option value="' + j[i].product_id + '~' +j[i].product_name+ '~' +j[i].sale_price +'">' + j[i].product_name + ' (Harga: '+ j[i].sale_price +')</option>';
                  }
                  $("select#slProduct").removeAttr('disabled');
                  $("select#slProduct").html(options);
            })
        }
      });

    var stok = 0;
    $("select#slProduct").change(function(){
         if(this.value != ""){
             var prod = $("#slProduct").val().split("~");
             stok = prod[3];
         }

      });


    function cekStok(num){

        if (eval(num) > eval(stok)){
            //alert("Jumlah stok tidak mencukupi");

            bootbox.dialog({
                    message: "<span class='bigger-110'>Jumlah stok tidak mencukupi</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });

            $("#qty").val(stok);
            return false
        }
        

        return true;
    }

    function validateNumber(evt) {

        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
      }


    var idRow = 1;
    var totalHarga = 0;
    jQuery("#btnTambah").click( function(){

        var prod = $('#slProduct').val();
        var arrProd = prod.split("~");
        var prodId = arrProd[0];
        var prodName = arrProd[1];
        var prodPrice = arrProd[2];
        var sup = $('#slSuplier').val().split("-");
        var agent = $('#slAgen').val().split("-");
        var qty = $('#qty').val();

        if (sup == "" || prod == "" || qty == 0){
            
            bootbox.dialog({
                    message: "<span class='bigger-110'>Data tidak lengkap</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });

            return false;
        }

        if (isAgent != "" && eval(qty)%minOrder > 0){
            
            bootbox.dialog({
                    message: "<span class='bigger-110'>Minimal pembelian adalah "+minOrder+" dan kelipatannya.</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });
            return false;
        }

        //Cek apakah produk yg sama sdh ditambahkan sebelumnya
        var dataGrid = jQuery("#grid-table").jqGrid('getRowData');
        if (dataGrid != ""){
            for (x=0; x<dataGrid.length; x++){
                if (dataGrid[x]["prodid"] == prodId && dataGrid[x]["agentId"] == agent[0]){
                    
                    bootbox.dialog({
                            message: "<span class='bigger-110'>Produk "+prodName+" dengan Supplier "+sup[1]+" dan Agen "+agent[1]+" sudah ditambahkan sebelumnya.</span>",
                            buttons:
                            {
                                    "button" :
                                     {
                                            "label" : "<i class='icon-ok'></i> Ok",
                                            "className" : "btn-sm btn-primary",
                                            //"callback": function() {
                                                    //Example.show("great success");
                                            //}
                                    }
                            }
                    });

                    return false;
                }
            }
        }

        
        var total = eval(prodPrice)*eval(qty);        

        var datarow = {no:idRow,suplierId:sup[0],suplier:sup[1],agentId:agent[0],agent:agent[1],prodid:prodId,prodname:prodName,price:prodPrice,qty:qty,total:total,del:"<a hrer='javascript: void(0)' onclick='delrow("+idRow+")'>Hapus</a>"};
        var su=jQuery("#grid-table").jqGrid('addRowData',idRow,datarow);
        if(su){
            totalHarga = totalHarga+total;
            setTotalHarga(totalHarga);

            var datarow2 = {no:idRow,suplierId:sup[0],suplier:sup[1],agentId:agent[0],agent:agent[1],prodid:prodId,prodname:prodName,price:prodPrice,qty:qty,total:total};
            jQuery("#grid-table2").jqGrid('addRowData',idRow,datarow2);
            idRow++;
            //alert("Succes. Write custom code to add data in server");
        }
        else {

            bootbox.dialog({
                    message: "<span class='bigger-110'>Produk gagal ditambahkan.</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });
        }
    });

    
    function delrow(id){

        var ret = jQuery("#grid-table").jqGrid('getRowData',id);
        var tot = eval(ret.total);
        //jQuery("#grid-table").jqGrid('delRowData',id);
        var su=jQuery("#grid-table").jqGrid('delRowData',id);
        if(su){
            totalHarga = totalHarga-tot;
            setTotalHarga(totalHarga);
            
            var su2 = jQuery("#grid-table2").jqGrid('delRowData',id);
            if(su2){
                //
            }
            //alert(2);
            //alert("Succes. Write custom code to delete row from server");
        }
        else {
            //alert(3);
            //alert("Allready deleted or not in list");
        }
    }

    function setTotalHarga(totalHarga){
        document.getElementById("lbTotalHarga").innerHTML = "<b>Total Harga: "+formatCurrency(totalHarga)+"</b>";
        document.getElementById("lbTotalHarga2").innerHTML = "<b>Total Harga: "+formatCurrency(totalHarga)+"</b>";

        $('#totalHarga').val(totalHarga);

        //Jika bukan agent
        if (isAgent == ""){
            if (totalPoint < totalHarga){
                document.getElementById("rdTukarPoint").disabled = true;
                $('#caraBayar').val("");
            }
            else{
                document.getElementById("rdTukarPoint").disabled = false;

            }
        }
    }


    jQuery("#grid-table").jqGrid({
        datatype: "local",
        height: 100,
        colNames:['No','suplierId','Suplier','agenId','Agen','ID Produk','Nama Produk','Harga','Jumlah','Total','Hapus'],
        colModel:[ {name:'no',index:'no', width:90, sorttype:"int", hidden:true},
                   {name:'suplierId',index:'suplierId', hidden:true},
                   {name:'suplier',index:'suplier', width:90, editable: false},
                   {name:'agentId',index:'agentId', hidden: true},
                   {name:'agent',index:'agent', width:90, editable: false},
                   {name:'prodid',index:'prodid', width:90, sorttype:"int", hidden:true},
                   {name:'prodname',index:'product_name', width:90, editable: false},
                   {name:'price',index:'price', width:90, align:"right", sorttype:"float", formatter: 'number', summaryType:'sum'},
                   {name:'qty',index:'qty', width:90, sorttype:"float", align:"right", formatter: 'number', summaryType:'sum'},
                   {name:'total',index:'total', width:90, sorttype:"float", align:"right", formatter: 'number', aggregator : 'sum', summaryType:'sum'},
                   {name:'del',index:'del', width:90, align:"center"}],
        autowidth: true,
        rownumbers: true,
        viewrecords: true,
        sortname: 'prodname',
        caption:"Data Pembelian"
        //editurl: "server.php",

    });


    jQuery("#grid-table2").jqGrid({
        datatype: "local",
        height: 100,
        colNames:['No','suplierId','Suplier','agenId','Agen','ID Produk','Nama Produk','Harga','Jumlah','Total'],
        colModel:[ {name:'no',index:'no', sorttype:"int", hidden:true},
                   {name:'suplierId',index:'suplierId', hidden:true},
                   {name:'suplier',index:'suplier', width:90, editable: false},
                   {name:'agentId',index:'agentId', hidden: true},
                   {name:'agent',index:'agent', width:90, editable: false},
                   {name:'prodid',index:'prodid', sorttype:"int", hidden:true},
                   {name:'prodname',index:'product_name', editable: false},
                   {name:'price',index:'price', width:90, sorttype:"int", align:"right", formatter: 'number', summaryType:'sum'},
                   {name:'qty',index:'qty', width:90, sorttype:"int", align:"right", formatter: 'number', summaryType:'sum'},
                   {name:'total',index:'total', width:90, sorttype:"int", align:"right", formatter: 'number', summaryType:'sum'}],

        autowidth: true,
        rownumbers: true,
        viewrecords: true,
        caption:"Data Pembelian"

    });



    function pilihBayar(val){
        $('#caraBayar').val(val);

        if (isAgent != ""){

            if (val == 3){

                document.getElementById("divBank").style.visibility = "visible";
                document.getElementById("divBank").style.position = "block";

            }else{

                document.getElementById("divBank").style.visibility = "hidden";
                document.getElementById("divBank").style.position = "absolute";
            }
        }
    }

    function cekProduct(){
        
        var jml = jQuery('#grid-table').jqGrid('getGridParam','records');
        
        if (jml == 0){
            
            bootbox.dialog({
                    message: "<span class='bigger-110'>Silahkan tambahkan produk.</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });
            return false;
        }
        else return true;
    }

    function konfirmasiPembelian(){

        var qty = $('#qty').val();
        var metodeBayar = $('#caraBayar').val();

        if (metodeBayar == ""){
            
            bootbox.dialog({
                    message: "<span class='bigger-110'>Pilih Metode Pembayaran.</span>",
                    buttons:
                    {
                            "button" :
                             {
                                    "label" : "<i class='icon-ok'></i> Ok",
                                    "className" : "btn-sm btn-primary",
                                    //"callback": function() {
                                            //Example.show("great success");
                                    //}
                            }
                    }
            });
            return false;
        }

        var bayar = "";
        if (metodeBayar == 1) bayar = "Cash";
        else if (metodeBayar == 2) bayar = "Tukar Point (Point Anda: <?php echo number_format($this->balance);?>)";
        else{
            bayar = document.getElementById("lbBank").innerHTML;
        }

        document.getElementById("lbMetodeBayar").innerHTML = "Metode Pembayaran: "+bayar;

        return true;

    }

    function finishWizard(){
        var dataGrid = jQuery("#grid-table2").jqGrid('getRowData');
        var dataJSON = JSON.stringify(dataGrid);
        
        var data = base64_encode(dataJSON);

        $('#dataPembelian').val(data);
        $('#inputForm').submit();
    }


    function formatCurrency(num) {
        num = num.toString().replace(/\Rp|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + num + '.' + cents);
    }

    function base64_encode(data) {
      //  discuss at: http://phpjs.org/functions/base64_encode/
      // original by: Tyler Akins (http://rumkin.com)
      // improved by: Bayron Guevara
      // improved by: Thunder.m
      // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // improved by: Rafa? Kukawski (http://kukawski.pl)
      // bugfixed by: Pellentesque Malesuada
      //   example 1: base64_encode('Kevin van Zonneveld');
      //   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
      //   example 2: base64_encode('a');
      //   returns 2: 'YQ=='

      var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = '',
        tmp_arr = [];

      if (!data) {
        return data;
      }

      do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
      } while (i < data.length);

      enc = tmp_arr.join('');

      var r = data.length % 3;

      return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
    }





</script>

<?php } ?>


